package com.glory.dgcpcpda.activity.recipe;

import android.os.Build;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.PERecipeListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.RecipeInfoEntity;
import com.glory.dgcpcpda.entity.RecipeListInfoEntity;
import com.glory.dgcpcpda.entity.UpdateIPEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: PERecipeActivity
 * Author: XJH
 * Date: 2020/5/14 11:17
 * Description:
 * History:
 */
public class PERecipeActivity extends BaseActivity {


    @BindView(R.id.etEqpNum)
    FreeUI_ClearEditText etEqpNum;
    @BindView(R.id.tvCurrentEqpType)
    TextView tvCurrentEqpType;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etPackageType)
    FreeUI_ClearEditText etPackageType;
    @BindView(R.id.etBDNo)
    FreeUI_ClearEditText etBDNo;
    @BindView(R.id.etWireSpec)
    FreeUI_ClearEditText etWireSpec;
    @BindView(R.id.etRecipeID)
    FreeUI_ClearEditText etRecipeID;
    @BindView(R.id.rbALL)
    RadioButton rbALL;
    @BindView(R.id.rbGold)
    RadioButton rbGold;
    @BindView(R.id.rbEQP)
    RadioButton rbEQP;
    @BindView(R.id.rbNewVersion)
    RadioButton rbNewVersion;
    @BindView(R.id.rbAllVersion)
    RadioButton rbAllVersion;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.rvPEList)
    RecyclerView rvPEList;
    @BindView(R.id.tvDownLoad)
    TextView tvDownLoad;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.list_tv6)
    TextView listTv6;
    @BindView(R.id.list_tv7)
    TextView listTv7;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.ivEqpTypeArrow)
    ImageView ivEqpTypeArrow;
    @BindView(R.id.flEqpTypeList)
    FrameLayout flEqpTypeList;
    @BindView(R.id.cbWorkTable)
    CheckBox cbWorkTable;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.etResin)
    FreeUI_ClearEditText etResin;
    @BindView(R.id.etCustomerCode)
    FreeUI_ClearEditText etCustomerCode;
    @BindView(R.id.etJmthickness)
    FreeUI_ClearEditText etJmthickness;
    @BindView(R.id.etWaferSize)
    FreeUI_ClearEditText etWaferSize;
    @BindView(R.id.etIspo)
    FreeUI_ClearEditText etIspo;
    @BindView(R.id.etMaterialType)
    FreeUI_ClearEditText etMaterialType;
    @BindView(R.id.etModelNo)
    FreeUI_ClearEditText etModelNo;
    @BindView(R.id.cbIsDown)
    CheckBox cbIsDown;
    @BindView(R.id.tvPackageName)
    TextView tvPackageName;
    @BindView(R.id.tvBdName)
    TextView tvBdName;
    private LotInfoEntity mLotInfoEntity = new LotInfoEntity();
    private String mRecipeType = "ALL";
    private int mState = 2;
    private int position = -1;
    private PERecipeListAdapter mPERecipeListAdapter;
    private List<String> mEqpType = new ArrayList<>();
    private FreeUI_GeneralPop mEqpTypePop;
    private String mProcessName = "";
    private String mPlantName = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_recipe_pe;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView() {
        setMainLayout(llMain);
        tvTitle.setText("PE下载Recipe");
        tvBaseSubmit.setText("查询");
        listTv5.setVisibility(View.VISIBLE);
        listTv5.setText("芯片名");
        listTv6.setVisibility(View.VISIBLE);
        listTv6.setText("丝材规格");
        initRecyclerView(rvPEList, this);
        mPERecipeListAdapter = new PERecipeListAdapter(null);
        mPERecipeListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mPERecipeListAdapter.isFirstOnly(true);
        rvPEList.setAdapter(mPERecipeListAdapter);

        scrollView.setOnScrollChangeListener((View.OnScrollChangeListener) (view, i, i1, i2, i3) -> {
            if (!scrollView.canScrollVertically(1)) {
                if (!scrollView.canScrollVertically(-1)){
                    return;
                }
                if (position == -1)
                    return;

                if (position > 1){
                    searchRecipeList();
                }
            }
        });

        initEdit(etLotID, s -> {
            FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                    ("正在查询LOT信息",new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                    }.getType(), getSupportFragmentManager(), PERecipeActivity.this) {

                @Override
                public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onSuccess(response);
                    if (response.body().isSuccess(PERecipeActivity.this,true,getSupportFragmentManager())){
                        mLotInfoEntity = response.body().getResponse().getBody();
                        etPackageType.setText(mLotInfoEntity.getLOT().getMAINMATTYPE());
                        etBDNo.setText(mLotInfoEntity.getWIRINGNO());
                        int res=mLotInfoEntity.getWIRESPEC().indexOf("/",mLotInfoEntity.getWIRESPEC().indexOf("/")+1);
                        if(res>0){
                            etWireSpec.setText(mLotInfoEntity.getWIRESPEC().substring(0,res).toUpperCase());
                        }
                        else if(res<=0){
                            etWireSpec.setText(mLotInfoEntity.getWIRESPEC().toUpperCase());
                        }
                        etResin.setText(mLotInfoEntity.getLOT().getUDF().getRESIN());
                        etCustomerCode.setText(mLotInfoEntity.getLOT().getCUSTOMERCODE().length() == 4?
                                "GD"+mLotInfoEntity.getLOT().getCUSTOMERCODE():
                                mLotInfoEntity.getLOT().getCUSTOMERCODE());
                        etMaterialType.setText(mLotInfoEntity.getYANMO());
                        etModelNo.setText(mLotInfoEntity.getHUAPIAN());
                        etIspo.setText(mLotInfoEntity.getISPO());
                        etJmthickness.setText(mLotInfoEntity.getJMTHICKNESS());
                        etWaferSize.setText(mLotInfoEntity.getWAFERSIZE());
                    }
                }

                @Override
                public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                    super.onError(response);

                }
            };

            JsonObject map = new JsonObject();
            map.addProperty("ACTIONTYPE","LOTINFOBYID");
            map.addProperty("LOTID",s);
            map.addProperty("LOTALIAS","");
            map.addProperty("DURABLE","");
            map.addProperty("EQUIPMENTID",getText(etEqpNum));
            NetUtils.requestPostNet("CPC.LOTQUERY","LOTQUERY",PERecipeActivity.this,map,callBack);
        });

        initEdit(etEqpNum, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {
                FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                        (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            UpdateIPEntity body = response.body().getResponse().getBody();
                            tvEqpType.setText(body.getPROGRAM_TYPE());
                            tvCurrentEqpType.setText(body.getPROGRAM_TYPE());
                            mProcessName = body.getPROCESSNAME();
                            mPlantName = body.getFAB();
                            requestEqpList();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "GETEQPINFOBYEQPID");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("EQPID",s);
                NetUtils.requestPostNet("EAP.GETEQPINFOBYEQPID","GETEQPINFOBYEQPID", PERecipeActivity.this,map,callBack);

            }
        });
    }

    private void requestEqpList() {
        FreeUI_EntityCallBack<BaseResponseBean<List<String>>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<List<String>>>
                (new TypeToken<BaseResponseBean<List<String>>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<List<String>>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    mEqpType = response.body().getResponse().getBody();
                    mEqpTypePop = null;  // 重置菜单
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<List<String>>> response) {
                super.onError(response);
                loadError(response.getException(), "GETEQPTYPEBYTYPE");
            }
        };
        JsonObject map = new JsonObject();
        //map.addProperty("PROCESS",mProcessName);
        map.addProperty("EQPTYPE",tvEqpType.getText().toString());
        NetUtils.requestPostNet("GETEQPTYPEBYTYPE", "GETEQPTYPEBYTYPE", this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.rbALL, R.id.rbGold, R.id.rbEQP, R.id.rbNewVersion, R.id.rbAllVersion, R.id.tvDownLoad, R.id.tvBaseSubmit,R.id.flEqpTypeList,R.id.cbIsDown})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rbALL:
                if (!tvCurrentEqpType.getText().toString().equals(tvEqpType.getText().toString())) {
                    rbGold.setChecked(true);
                    return;
                }
                mRecipeType = "ALL";
                break;
            case R.id.rbGold:
                mRecipeType = "GOLD";
                break;
            case R.id.rbEQP:
                if (!tvCurrentEqpType.getText().toString().equals(tvEqpType.getText().toString())) {
                    rbGold.setChecked(true);
                    return;
                }
                mRecipeType = "EQP";
                break;
            case R.id.rbNewVersion:
                mState = 2;
                break;
            case R.id.rbAllVersion:
                mState = 3;
                break;
            case R.id.tvDownLoad:
                if (mPERecipeListAdapter.getSelectorData() == null) {
                    showToast("请选择Recipe信息", false);
                    return;
                }

                RecipeInfoEntity entity = mPERecipeListAdapter.getSelectorData();
                //上传、下载、切换
                JsonObject map = new JsonObject();
                map.addProperty("PlantName",mPlantName);
                map.addProperty("ProcessName",mProcessName);
                map.addProperty("EqpID",getText(etEqpNum));
                map.addProperty("RecipeEqpID",entity.getRecipeEqpID());
                map.addProperty("RecipeID",entity.getRecipeID());
                map.addProperty("EnableEQ",0);
                map.addProperty("RecipeVer",entity.getRecipeVer());
                map.addProperty("LotID",getText(etLotID));
                map.addProperty("id",entity.getId());
                sendEqpRecipe(map,"CPC.SendEqpRecipe","SendEqpRecipe");
//                LotUtils.recipeDownLoad(this, getSupportFragmentManager(), mPERecipeListAdapter.getSelectorData(),
//                        getText(etEqpNum),getText(etLotID),-1);
                break;
            case R.id.tvBaseSubmit:
                if (getText(etEqpNum).equals("") || tvEqpType.getText().toString().equals("")) {
                    showToast("设备号或设备类型不能为空", false);
                    return;
                }

//                if (getText(etBDNo).equals("") && getText(etWireSpec).equals("") && getText(etPackageType).equals("")){
//                    showToast("封装形式、丝材规格、BD图号，至少填一个",false);
//                    return;
//                }
                position = 1;

                searchRecipeList();
                break;
            case R.id.flEqpTypeList:
                if (mEqpType.size() <= 0) {
                    showToast("未获取到设备类型列表", false);
                    return;
                }

                if (mEqpTypePop != null) {
                    if (mEqpTypePop.isShowing()) {
                        mEqpTypePop.dismiss();
                    }
                } else {
                    mEqpTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEqpTypeList.getWidth(), mEqpType, ivEqpTypeArrow, (codeS, i) -> {
                        tvEqpType.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivEqpTypeArrow);
                mEqpTypePop.showAsDropDown(flEqpTypeList, 0, 0);
                break;
            case R.id.cbIsDown:
                if (cbIsDown.isChecked()){
                    if(mProcessName.equals("CT")){
                        etPackageType.setText("模板程序");
                    }else {
                        etBDNo.setText("模板程序");
                    }
                    etLotID.setFocusable(false);
                    etLotID.setFocusableInTouchMode(false);
                }else {
                    etBDNo.setText("");
                    etPackageType.setText("");
                    etLotID.setFocusable(true);
                    etLotID.setFocusableInTouchMode(true);
                }
                break;
        }
    }

    private void sendEqpRecipe(JsonObject map, String messageName, String message) {
        String tips = "";
        switch (message){
            case "UploadRecipeAsync":
                tips = "正在上传程序";
                break;
            case "SendEqpRecipe":
                tips = "正在下载程序";
                break;
            case "SwitchEqpRecipe":
                tips = "正在切换程序";
                break;
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (tips,new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    if (message.equals("UploadRecipeAsync")){
                        sendEqpRecipe(map,"CPC.SendEqpRecipe","SendEqpRecipe");
                    }else if (message.equals("SendEqpRecipe")){
                        sendEqpRecipe(map,"CPC.SwitchEqpRecipe","SwitchEqpRecipe");
                    }else {
                        showConfirmDialog(PERecipeActivity.this,"下载成功");
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),message);

            }
        };
        NetUtils.requestPostNet(messageName,message, this,map,callBack);
    }

    private void searchRecipeList() {

        if (cbIsDown.isChecked()) {
            if (mLotInfoEntity == null){
                mLotInfoEntity = new LotInfoEntity();
            }
        }

        FreeUI_EntityCallBack<BaseResponseBean<RecipeListInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<RecipeListInfoEntity>>
                (new TypeToken<BaseResponseBean<RecipeListInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<RecipeListInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    RecipeListInfoEntity body = response.body().getResponse().getBody();
                    if (body.getRecipeList().size() <= 0){
                        showToast("暂无更多数据",false);
                        position = -1;
                        return;
                    }

                    if (position == 1){
                        mPERecipeListAdapter.getData().clear();
                        mPERecipeListAdapter.notifyDataSetChanged();
                    }

                    for (RecipeInfoEntity recipeInfoEntity : body.getRecipeList()){
                        recipeInfoEntity.setPlantName(body.getPlantName());
                        recipeInfoEntity.setProcessName(body.getProcessName());
                    }
                    mPERecipeListAdapter.addData(body.getRecipeList());
                    position++;

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<RecipeListInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetRecipeListByPE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("pageNo",position);
        map.addProperty("pageSize",10);
        map.addProperty("PlantName",mPlantName);
        map.addProperty("ProcessName",mProcessName);
        map.addProperty("EqpID", getText(etEqpNum));
        map.addProperty("LotID", getText(etLotID));
        map.addProperty("EqpType",tvEqpType.getText().toString());
        map.addProperty("RecipeType", mRecipeType);
        map.addProperty("RecipeID", getText(etRecipeID));
        map.addProperty("PkgType", getText(etPackageType));
        map.addProperty("BDID", getText(etBDNo));
        map.addProperty("WireType", getText(etWireSpec));
        map.addProperty("DeviceName", mLotInfoEntity.getPRODUCTMODEL());
        map.addProperty("ChipName", mLotInfoEntity.getCHIPNAME());
        map.addProperty("Status", mState);
        map.addProperty("consPro", cbWorkTable.isChecked());
        map.addProperty("Resin",getText(etResin));
        map.addProperty("Customercode",getText(etCustomerCode));
        map.addProperty("Wafersize",getText(etWaferSize));
        map.addProperty("Jmthickness",getText(etJmthickness));
        map.addProperty("ISPO",getText(etIspo));
        map.addProperty("Materialtype",getText(etMaterialType));
        map.addProperty("ModelNo",getText(etModelNo));
        NetUtils.requestPostNet("CPC.GetRecipeListByPE", "GetRecipeListByPE", this, map, callBack);
    }

}
